package string;

import com.sun.org.apache.bcel.internal.classfile.Code;

import java.util.Random;
import java.util.Scanner;

//1. 生成一个4位验证码(数字和字母的组合)，输出到控制台并提示用户输入验证码，输入后若正确则提示验证码正确，若错误则提示验证码错误。注意：不区分大小写
public class IdentifyingCode {
    public static void main(String[] args) {
        passingTest();
    }

    private static void passingTest() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            String code = getCode();
            System.out.println("验证码为:" + code);
            System.out.println("请输入验证码");
            String code2 = sc.next();
            String s1 = code.toLowerCase();
            String s2 = code2.toLowerCase();
            if (s1.equals(s2)) {
                System.out.println("验证码正确!");
                break;
            } else {
                System.out.println("验证码错误!");
                continue;
            }
        }
    }

    private static String getCode() {
        Random r = new Random();
        String str = "";
        char[] c = new char[62];
        for (int i = 0; i < c.length; i++) {
            if (i <= 25) {
                c[i] = (char) ('A' + i);
            } else if (i <= 52) {
                c[i] = (char) ('a' + i - 26);
            } else {
                c[i] = (char) ('0' + i - 52);
            }
        }

        for (int i = 0; i < 5; i++) {
            str += c[r.nextInt(c.length)];
        }
        return str;
    }
}
